//
//  KLBookListTableViewController.m
//  KLBookStore
//
//  Created by apple on 2017/10/16.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "KLBookListTableViewController.h"
#import "KLBookEntity.h"
#import "KLBookService.h"

#import "KLBookListTableViewCell.h"
#import "KLBookListTableViewCell+BookEntity.h"

#import "KLBookDetailController.h"

#import "MJRefresh.h"

@interface KLBookListTableViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<KLBookEntity *> *bookEntites;
@property (nonatomic, assign, getter=isFirstLoad) BOOL firstLoad;//用于判断数据是否已经加载过一遍

@end

@implementation KLBookListTableViewController

#pragma mark - vc life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FavorBookNotificationAction:) name:@"FavorBookNotification" object:nil];
    
    self.firstLoad = YES;
    [self initTableView];
    [self getDataWithOffset:0 pageSize:KLDefaultPageSize];
    
    __unsafe_unretained UITableView *tableView = self.tableView;
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉加载更多
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self getDataWithOffset:self.bookEntites.count pageSize:KLDefaultPageSize];
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (!self.isFirstLoad) {
        //        [self getDataWithOffset:0 pageSize:self.bookEntites.count];
        //        [self.tableView reloadData];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.firstLoad = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"FavorBookNotification" object:self];
}

#pragma mark - view init
- (void)initTableView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.backgroundColor = UIColorFromHexRGB(0xF9F9F9);
    tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    tableView.tableFooterView = [UIView new];
    tableView.delegate = self;
    tableView.dataSource = self;
    self.tableView = tableView;
    [self.view addSubview:tableView];
}

#pragma mark - data
- (void)getAllData {
    __weak typeof(self) weakSelf = self;
    [KLBookService getAllBookEntitiesWithCompletion:^(NSArray<KLBookEntity *> *bookEntites) {
        self.bookEntites = [bookEntites mutableCopy];
        [weakSelf.tableView reloadData];
    }];
}

- (void)getDataWithOffset:(long long)offset pageSize:(NSUInteger)size {
    if (offset == 0) {
        [self.bookEntites removeAllObjects];
    }
    __weak typeof(self) weakSelf = self;
    [KLBookService getBookEntitiesWithOffset:offset pageSize:size completion:^(NSArray<KLBookEntity *> *bookEntites) {
        [self.bookEntites addObjectsFromArray:bookEntites];
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView reloadData];
    }];
}

#pragma mark - notification
- (void)FavorBookNotificationAction:(NSNotification *)notification{
//    [self getDataWithOffset:0 pageSize:self.bookEntites.count];//这边还是原先的count，会出问题，所以重新刷新
    [self getDataWithOffset:0 pageSize:KLDefaultPageSize];
    NSLog(@"---接收到通知 tableView---");
}

#pragma mark - table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.bookEntites.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifer = @"bookListTableViewCell";
    KLBookListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (cell == nil) {
        cell = [[KLBookListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    KLBookEntity *book = [self.bookEntites objectAtIndex:indexPath.row];
    [cell configureWithBookEntity:book];
    
    //如果在滚动中 不去设置图片 停止滚动后再开始设置图片
    if (!cell.coverImageView.image) {
        if (tableView.dragging == NO && tableView.decelerating == NO) {
            [cell startDownloadCoverImageWithBookEntity:book];
        }
    }
    
    return cell;
}

#pragma mark - table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    KLBookEntity *book = [self.bookEntites objectAtIndex:indexPath.row];
    KLBookDetailController *detailVc = [[KLBookDetailController alloc] init];
    detailVc.bookEntity = book;
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"取消收藏";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        KLBookEntity *book = [self.bookEntites objectAtIndex:indexPath.row];
        [KLBookService deleteBookWithId:book.id completion:^(BOOL success) {
            if (success) {
                [tableView beginUpdates];
                [self.bookEntites removeObject:book];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                [tableView endUpdates];
            }
        }];
//        BOOL success =  [KLBookService deleteBookWithId:book.id];
//        if (success) {
//            [tableView beginUpdates];
//            [self.bookEntites removeObject:book];
//            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//            [tableView endUpdates];
//        }
    }
}

#pragma mark - scroll view delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self loadCoverImageForVisibleCells];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self loadCoverImageForVisibleCells];
}

- (void)loadCoverImageForVisibleCells {
    NSArray<KLBookListTableViewCell *> *visibleCells = [self.tableView visibleCells];
    for (KLBookListTableViewCell *cell in visibleCells) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        KLBookEntity *book = [self.bookEntites objectAtIndex:indexPath.row];
        if (!cell.coverImageView.image) {
            [cell startDownloadCoverImageWithBookEntity:book];
        }
    }
}

#pragma mark - lazy load
- (NSMutableArray<KLBookEntity *> *)bookEntites {
    if (!_bookEntites) {
        _bookEntites = [@[] mutableCopy];
    }
    return _bookEntites;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
